import { createRouter, createWebHashHistory } from "vue-router";
import type { RouteRecordNormalized, RouteRecordRaw } from "vue-router";
import { useHomeStore } from "/@/stores/home";
import { useMenuStore } from "/@/stores/menu";
import { useI18n } from "/@/locales/useI18n";
import { handleLog } from "/@/base/log";
import { ApplicationItem } from "/@/api/models";
const TagLog = handleLog(true, true);

export const MAIN_ROUTE_NAME = "main";

interface AppRouteItem {
  name: string;
  appId: number;
  isInit: boolean;
  routeData: RouteRecordRaw[];
}

export const FIRST_ROUTE = `/${MAIN_ROUTE_NAME}`;
export const appRouteData: AppRouteItem[] = [{ name: MAIN_ROUTE_NAME, appId: -1, isInit: false, routeData: [] }];
export function resetRouter() {
  isInitAppData = false;
  appRouteData.forEach((item) => {
    item.isInit = false;
    item.routeData.forEach((route: RouteRecordRaw) => {
      router.removeRoute(route.name as string);
    });
    item.routeData = [];
  });
}
let isInitAppData = false;
export function setAppData(appData: ApplicationItem[]) {
  appRouteData.forEach((el) => {
    //以应用编码作为应用根路由的名称和路由
    const app = appData.find((item) => el.name === item.code);
    if (app) {
      el.appId = app.id as number;
    }
  });
  isInitAppData = true;
}
const routes: Array<RouteRecordRaw> = [
  {
    path: `/${MAIN_ROUTE_NAME}`,
    name: MAIN_ROUTE_NAME,
    component: () => import(`../views/Home.vue`),
    children: [
      {
        path: "404",
        name: `${MAIN_ROUTE_NAME}-404`,
        component: () => import("../views/404.vue"),
      },
      {
        path: "401",
        name: `${MAIN_ROUTE_NAME}-401`,
        component: () => import("../views/401.vue"),
      },
    ],
  },
  {
    path: "/",
    name: "root",
    component: () => import(`../views/Login.vue`),
  },
  {
    path: "/test",
    name: "test",
    component: () => import(`../views/Test.vue`),
  },
  {
    path: "/login",
    name: "login",
    component: () => import(`../views/Login.vue`),
  },
  {
    path: "/:pathMatch(.*)",
    component: () => import("../views/404.vue"),
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
let curApp: AppRouteItem | null = null;
router.beforeEach(async (to, _from, next) => {
  let { path, name: routeName } = to;
  TagLog("going to route", to);
  //链接是否以其中一个应用路由开头
  const targetApp = appRouteData.find((app) => path.indexOf(`/${app.name}`) === 0);
  if (!targetApp) {
    // console.log("not found app", appRouteData, path);
    next();
    return;
  }
  const homeStore = useHomeStore();
  homeStore.togglePageLoading({ loading: true });
  if (!isInitAppData) {
    isInitAppData = true;
    //初始化 加载应用数据
    setAppData(homeStore.applicationData);
    TagLog("setAppData", targetApp);
  }
  if (curApp) {
    if (targetApp.name !== curApp.name) {
      //切换应用 重新加载菜单数据
      resetRouter();
    }
  }
  curApp = targetApp;
  let targetRoute: RouteRecordNormalized | null = null;
  if (!targetApp.isInit) {
    //该根应用还没初始化其下面的菜单数据 开始初始化
    targetApp.isInit = true;
    const { t } = useI18n();
    // notification.info({
    //   message: t("common.tip"),
    //   description: t("aiot.home.loadingMenu"),
    //   duration: null,
    // });
    try {
      const menuStore = useMenuStore();
      TagLog("initAuthMenu start");
      const routeData = await menuStore.initAuthMenu({
        rootRouteName: targetApp.name,
      });
      TagLog("initAuthMenu done", routeData);
      if (!routeData) {
        targetApp.isInit = false;
        // notification.destroy();
        next({ name: "login" });
        return;
      }
      targetApp.routeData = routeData;
    } catch (err) {
      console.warn("initAuthMenu error", err);
      targetApp.isInit = false;
    }
    // notification.destroy();
    const routes = router.getRoutes();
    TagLog("all routes", routes);
    for (const route of routes) {
      if (route.path === path) {
        targetRoute = route;
        break;
      }
    }
  }
  if (targetRoute) {
    TagLog("going to targetRoute", targetRoute, routeName);
    next(targetRoute);
    return;
  }
  next();
});
router.afterEach(() => {
  const homeStore = useHomeStore();
  homeStore.togglePageLoading({ loading: false });
  homeStore.contentScrollable = true;
});
export default router;
